package com.kaishengit.web;


import java.io.IOException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaishengit.dao.OrderDao;
import com.kaishengit.dao.ProdDao;
import com.kaishengit.entity.Prod;
import com.kaishengit.entity.User;
import com.kaishengit.util.StringUtil;

public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String method=request.getParameter("m");
		if(StringUtil.isEmpty(method)){
			list(request,response);
		}else if("show".equals(method)){
			show(request,response);
		}else if("addorder".equals(method)){
			String httpMethod=request.getMethod();
			if("GET".equals(httpMethod)){
				toAddOrder(request,response);
			}else if("POST".equals(httpMethod)){
				addOrder(request,response);
			}
			
		}
	}
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/shopcar.jsp").forward(request, response);
	}
	private void addOrder(HttpServletRequest request,
			HttpServletResponse response) {
		
	}
	private void toAddOrder(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/order.jsp").forward(request, response);
	}
	private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		OrderDao orderDao=new OrderDao();
		ProdDao prodDao=new ProdDao();
		User user=(User)request.getSession().getAttribute("user");
		List<Map<String, Object>> list=orderDao.findByUserId(user.getId());
		for(Map<String, Object> map : list){
			List<Prod> prodList=prodDao.findByOrderId((String)map.get("id"));
			String names=prodNameList(prodList);
			map.put("names", names);
		}
		request.setAttribute("list", list);
		request.getRequestDispatcher("/WEB-INF/views/myorder.jsp").forward(request, response);
	}
	private String prodNameList(List<Prod> prodList){
		StringBuffer buffer=new StringBuffer();
		for(Prod p:prodList){
			buffer.append(p.getProdname()).append(",");
		}
		String str=buffer.toString();
		return str.substring(0,str.length()-1);
	}
}
